# -*- coding: utf-8 -*-
"""
生成 web-doctor/python/analysis.html 的示例脚本（使用 Plotly）。
运行：
  python web-doctor/python/generate_charts.py
依赖：
  pip install plotly
说明：
  - 读取 web-doctor/data/sample-data.json
  - 生成两个图：最新 T 分数柱状图、风险分布饼图
  - 输出为 web-doctor/python/analysis.html（可由 index.html 通过 iframe 引用）
"""
from __future__ import annotations
import json
from pathlib import Path
import plotly.graph_objects as go
from plotly.subplots import make_subplots

ROOT = Path(__file__).resolve().parents[1]
SAMPLE = ROOT / 'data' / 'sample-data.json'
OUT = ROOT / 'python' / 'analysis.html'


def main():
    data = json.loads(SAMPLE.read_text(encoding='utf-8'))
    patients = data['patients']

    names = [p['name'] for p in patients]
    latest_t = [ (p.get('bmd') or [{}])[-1].get('tScore') for p in patients ]

    risk_cnt = {'高':0, '中':0, '低':0}
    for p in patients:
        risk_cnt[p.get('riskLevel','低')] = risk_cnt.get(p.get('riskLevel','低'),0) + 1

    fig = make_subplots(rows=1, cols=2, specs=[[{'type':'xy'},{'type':'domain'}]],
                        subplot_titles=("最新T分数", "风险分布"))

    colors = ['#198754' if (v is not None and v >= -1) else '#ffc107' if (v is not None and v >= -2.5) else '#dc3545' for v in latest_t]
    fig.add_trace(go.Bar(x=names, y=latest_t, marker_color=colors, name='Tscore'), row=1, col=1)
    fig.add_trace(go.Pie(labels=['高','中','低'], values=[risk_cnt['高'], risk_cnt['中'], risk_cnt['低']], hole=0.45,
                         marker=dict(colors=['#dc3545','#ffc107','#198754'])), row=1, col=2)

    fig.update_layout(height=420, width=1100, showlegend=True, margin=dict(l=20,r=20,t=40,b=20))

    OUT.parent.mkdir(parents=True, exist_ok=True)
    fig.write_html(str(OUT), include_plotlyjs='cdn')
    print(f'Wrote {OUT}')


if __name__ == '__main__':
    main()
